package com.ideal.wxlogin.controller;


import com.alibaba.fastjson.JSONObject;
import com.ideal.wxlogin.result.Result;
import com.ideal.wxlogin.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WeChatService weChatService;

    /**
     * 微信公众号消息回调 get方法用于微信鉴权
     *
     * @param signature 微信的签名，需要与自己生成的签名进行比对，相同则成功
     * @param timestamp 时间戳
     * @param nonce
     * @param echostr
     * @return String
     */
    @GetMapping(value = "/callback",produces = "text/plain;charset=UTF-8")
    public String checkToken(@RequestParam(name = "signature") String signature,
                             @RequestParam(name = "timestamp") String timestamp,
                             @RequestParam(name = "nonce") String nonce,
                             @RequestParam(name = "echostr") String echostr) {
        try {
            log.info("-----签名验证开始-----");
            String newStr = weChatService.checkToken(signature, timestamp, nonce, echostr);
            if (!echostr.equals(newStr)) {
                log.error("-----签名验证失败-----");
                return "error";
            }
            log.info("-----签名验证成功-----");
            return echostr;
        } catch (Exception e) {
            return "error";
        }

    }

    @PostMapping("/callback")
    public void callEvent(@RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr,
                          @RequestParam(name = "openid", required = false) String openid,
                          @RequestBody String msg) {
        weChatService.handleWechatCallBack(msg, signature, timestamp, nonce, echostr, openid);
    }

    @GetMapping("/qrcode")
    public Result getQrcode() {
        String resp = weChatService.getQrcode();
        return Result.success(JSONObject.parseObject(resp));
    }

    @GetMapping("/check_login_status")
    public Result checkLoginStatus(@RequestParam String ticket) {
        String openId = weChatService.checkLoginStatus(ticket);
        if(openId == null || openId.equals("none")) {
            return Result.success(null);
        }
        return Result.success(openId);
    }
}